<template>
  <AppNavbar @search="handleSearch" v-model:searchKey="searchKey"/>


  <div class="profile-container">
    <!-- 顶部用户信息卡片 -->
    <div class="user-card">
      <div class="user-banner" :style="{ backgroundImage: `url('/pic/banner.avif')` }"></div>
      <div class="user-info">
        <div class="avatar-container">
          <el-avatar :size="100" :src="userInfo.avatar" class="user-avatar"/>

        </div>
        <div class="user-details">
          <div class="username">
            <h2>{{ userInfo.nickname }}</h2>
            <el-tag type="danger" size="small" effect="dark">小会员</el-tag>
            <!--            <el-tag v-if="userInfo.vip" type="danger" size="small" effect="dark">小会员</el-tag>-->
          </div>
          <div class="signature">{{ userInfo.bio || '这个人很什么，什么都没写' }}</div>
          <div class="stats">
            <div class="stat-item">
              <span class="stat-number">{{ userInfo.allFollow }}</span>
              <span class="stat-label">关注</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ userInfo.allFans }}</span>
              <span class="stat-label">粉丝</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ userInfo.allLikes }}</span>
              <span class="stat-label">获赞</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 导航菜单 -->
    <div class="profile-nav">
      <el-menu
          :default-active="activeTab"
          mode="horizontal"
          class="nav-menu"
          @select="handleTabChange"
      >
        <el-menu-item index="home">
          <el-icon>
            <User/>
          </el-icon>
          <span>主页</span>
        </el-menu-item>
        <el-menu-item index="videos">
          <el-icon>
            <VideoCamera/>
          </el-icon>
          <span>投稿</span>
        </el-menu-item>
        <el-menu-item index="favorites">
          <el-icon>
            <Star/>
          </el-icon>
          <span>收藏</span>
        </el-menu-item>
        <el-menu-item index="history">
          <el-icon>
            <Clock/>
          </el-icon>
          <span>历史</span>
        </el-menu-item>

      </el-menu>
    </div>

    <!-- 内容区域 -->
    <div class="profile-content">
      <!-- 主页内容 -->
      <div v-if="activeTab === 'home'" class="tab-content">


        <div class="section">
          <div class="section-header">
            <h3 class="section-title">我的投稿</h3>
            <el-link type="primary" :underline="false">查看全部</el-link>
          </div>


          <div class="video-grid">
            <VideoCard
                v-for="video in userVideos.slice(0, 8)"
                :key="video.id"
                :video="video"
                @click="handleVideoClick"
            />
          </div>





        </div>
      </div>

      <!-- 投稿内容 -->
      <div v-if="activeTab === 'videos'" class="tab-content">
        <div class="section">
          <div class="section-header">
            <h3 class="section-title">我的投稿</h3>
            <el-button type="primary" icon="Upload" @click="handleUpload">上传视频</el-button>
          </div>
          <el-table :data="userVideos" style="width: 100%">
            <el-table-column prop="title" label="标题" width="400">
              <template #default="{ row }">
                <div class="video-title-cell">
                  <el-image :src="row.coverUrl" fit="cover" class="cover-thumb"></el-image>
                  <span class="title-text">{{ row.title }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="views" label="播放" width="120" sortable>
              <template #default="{ row }">
                {{ formatViews(row.views) }}
              </template>
            </el-table-column>
            <el-table-column prop="likes" label="点赞" width="120" sortable>
              <template #default="{ row }">
                {{ formatViews(row.likes) }}
              </template>
            </el-table-column>
            <el-table-column prop="comments" label="评论" width="120" sortable>
              <template #default="{ row }">
                {{ formatViews(row.comments) }}
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="日期" width="120" sortable/>
            <el-table-column label="操作" width="120">
              <template #default>
                <el-button size="small">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 收藏内容 -->
      <div v-if="activeTab === 'favorites'" class="tab-content">
        <div class="section">
          <div class="section-header">
            <h3 class="section-title">我的收藏夹</h3>
            <el-button type="primary" icon="Plus" @click="showAddFavDialog = true">新建收藏夹</el-button>
          </div>
          <div class="favorites-main">
            <!-- 收藏夹列表 -->
            <div class="favorites-list">
              <el-menu
                :default-active="selectedFavId?.toString()"
                class="fav-menu"
                @select="handleFavSelect"
                style="border:none; background:transparent;"
              >
                <el-menu-item
                  v-for="fav in favoritesList"
                  :key="fav.id"
                  :index="fav.id.toString()"
                  class="fav-menu-item"
                >
                  <div class="fav-menu-content">
                    <span class="fav-name">{{ fav.name }}</span>
                    <div class="fav-tags-actions">
                      <el-tag v-if="fav.isPublic === 1" size="small" type="success" effect="plain">公开</el-tag>
                      <el-tag v-else size="small" type="info" effect="plain">私密</el-tag>
                      <el-popconfirm v-if="!fav.isDefault && fav.id !== 1" title="确定删除该收藏夹？" @confirm="() => handleDelFavorites(fav.id)">
                        <template #reference>
                          <el-button icon="Delete" size="small" circle text style="margin-left:8px;" @click.stop></el-button>
                        </template>
                      </el-popconfirm>
                    </div>
                  </div>
                </el-menu-item>
              </el-menu>
            </div>
            <!-- 收藏夹视频区 -->
            <div class="favorites-videos">
              <transition name="fade" mode="out-in">
                <div v-if="favVideosLoading" class="fav-loading" key="loading"><el-skeleton rows="4" animated/></div>
                <div v-else-if="favVideos.length === 0" class="fav-empty" key="empty">
                  <el-empty
                      description="暂无视频数据"
                      :image-size="200"/>



                </div>
                <div v-else class="video-grid" key="videos">
                  <VideoCard
                    v-for="video in favVideos"
                    :key="video.id"
                    :video="video"
                    @videoClick="handleVideoClick"
                  />
                </div>
              </transition>
            </div>
          </div>
        </div>
        <!-- 新建收藏夹弹窗 -->
        <el-dialog v-model="showAddFavDialog" title="新建收藏夹" width="400px" @close="resetAddFavForm">
          <el-form :model="addFavForm" label-width="80px">
            <el-form-item label="名称">
              <el-input v-model="addFavForm.name" maxlength="20" show-word-limit placeholder="请输入收藏夹名称"/>
            </el-form-item>
            <el-form-item label="公开">
              <el-switch v-model="addFavForm.isPublic" active-value="1" inactive-value="0"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showAddFavDialog = false">取消</el-button>
            <el-button type="primary" @click="handleAddFavorites">确定</el-button>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>


</template>

<script setup>
import {onMounted, ref} from 'vue'
import {Clock, Star, User, VideoCamera, View, Plus, Delete} from '@element-plus/icons-vue'

import AppNavbar from '@/components/AppNavbar.vue'
import VideoCard from '@/components/VideoCard.vue'
import {useRouter, useRoute} from "vue-router";
import {getVideosByUserId, getVideosByFavoritesId} from "@/api/vidoe.js";
import {getInfoById} from "@/api/user.js";
import {useVideoStore} from "@/api/stores/usevideoStore.js";
import {addFavorites, delFavorites, getFavoritesByUserId} from "@/api/favorites.js";





const router = useRouter()
const route = useRoute()
const videoStore = useVideoStore()

// 当前激活的标签页
const activeTab = ref('home')
const favoritesTab = ref('videos')

// 得到用户的信息  和上传的视频等信息
onMounted(() => {
  const userId = route.params.id;
  if (userId) {
    getInfo(userId);
    getUserVideos(userId);
    fetchFavoritesList();
  }
})
async function getInfo(uId){
   const res = await   getInfoById(uId)
  userInfo.value=res.userInfo

}
// 用户信息
const userInfo = ref({})

// const userInfo = ref({
//   nickname: '前端开发者',
//   avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
//   banner: 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?ixlib=rb-4.0.3&auto=format&fit=crop&w=1200&q=80',
//   bio: '前端开发工程师 | Vue技术爱好者 | 开源贡献者 专注于Web前端开发，热爱探索新技术，乐于分享开发经验。',
//   allFollow: 128,
//   allFans: 2546,
//   allLikes: 12345
// })

// 用户投稿视频
const userVideos = ref([
  {
    id: 1,
    title: 'Vue3实战：构建响应式后台管理系统',
    coverUrl: 'https://images.unsplash.com/photo-1551650975-87deedd944c3?ixlib=rb-4.0.3&auto=format&fit=crop&w=400&q=80',
    views: 12345,
    likes: 1234,
    comments: 56,
    duration: '15:24',
    createdAt: '2023-06-15',
    nickname: '前端开发者'
  },
  {
    id: 2,
    title: 'Element Plus高级组件开发指南',
    coverUrl: 'https://images.unsplash.com/photo-1547658719-da2b51169166?ixlib=rb-4.0.3&auto=format&fit=crop&w=400&q=80',
    views: 8765,
    likes: 876,
    comments: 42,
    duration: '22:18',
    createdAt: '2023-06-10',
    nickname: '前端开发者'
  },
  {
    id: 3,
    title: 'CSS Grid布局完全指南',
    coverUrl: 'https://images.unsplash.com/photo-1581276879432-15e50529f34b?ixlib=rb-4.0.3&auto=format&fit=crop&w=400&q=80',
    views: 15678,
    likes: 1567,
    comments: 78,
    duration: '18:42',
    createdAt: '2023-06-05',
    nickname: '前端开发者'
  },
  {
    id: 4,
    title: 'TypeScript从入门到精通',
    coverUrl: 'https://images.unsplash.com/photo-1579403124614-197f69d8187b?ixlib=rb-4.0.3&auto=format&fit=crop&w=400&q=80',
    views: 23456,
    likes: 2345,
    comments: 123,
    duration: '32:15',
    createdAt: '2023-05-28',
    nickname: '前端开发者'
  },
  {
    id: 5,
    title: '前端性能优化实战技巧',
    coverUrl: 'https://images.unsplash.com/photo-1555066931-4365d14bab8c?ixlib=rb-4.0.3&auto=format&fit=crop&w=400&q=80',
    views: 19876,
    likes: 1987,
    comments: 87,
    duration: '25:48',
    createdAt: '2023-05-20',
    nickname: '前端开发者'
  }
])

// 得到用户投稿的视频

async function getUserVideos(uId) {
  const res = await getVideosByUserId(uId)
  if (res.code === 200){
    userVideos.value  =res.videos

  }


}

// 收藏夹相关
const favoritesList = ref([]) // 收藏夹列表
const selectedFavId = ref(null) // 当前选中的收藏夹id
const favVideos = ref([]) // 当前收藏夹下的视频
const favVideosLoading = ref(false)
const showAddFavDialog = ref(false)
const addFavForm = ref({ name: '', isPublic: 1 })

// 获取收藏夹列表
async function fetchFavoritesList() {
  const userId = route.params.id
  const res = await getFavoritesByUserId(userId)
  if (res && res.favorites) {
    favoritesList.value = res.favorites
    // 默认选中第一个收藏夹
    if (favoritesList.value.length > 0) {
      selectedFavId.value = favoritesList.value[0].id
      await fetchFavVideos(selectedFavId.value)
    } else {
      selectedFavId.value = null
      favVideos.value = []
    }
  }
}

// 获取收藏夹下的视频
async function fetchFavVideos(favId) {
  favVideosLoading.value = true
  favVideos.value = []
  const res = await getVideosByFavoritesId(favId)
  if (res && res.videos) {
    favVideos.value = res.videos
  }
  favVideosLoading.value = false
}

// 选择收藏夹
function handleFavSelect(favId) {
  selectedFavId.value = Number(favId)
  fetchFavVideos(selectedFavId.value)
}

// 新建收藏夹
async function handleAddFavorites() {
  if (!addFavForm.value.name) return
  const userId = route.params.id
  const payload = {
    name: addFavForm.value.name,
    isPublic: addFavForm.value.isPublic,
    userId: userId
  }
  const res = await addFavorites(payload)
  if (res && res.code === 200) {
    showAddFavDialog.value = false
    resetAddFavForm()
    await fetchFavoritesList()
  }
}
function resetAddFavForm() {
  addFavForm.value = { name: '', isPublic: 1 }
}
// 删除收藏夹
async function handleDelFavorites(favId) {
  const res = await delFavorites(favId)
  if (res && res.code === 200) {
    await fetchFavoritesList()
  }
}

// 格式化数字显示
const formatViews = (num) => {
  if (num > 10000) return `${(num / 10000).toFixed(1)}万`
  if (num > 1000) return `${(num / 1000).toFixed(1)}千`
  return num
}

const handleVideoClick = (video) => {
  videoStore.selectVideo(video)
  router.push(`/video/${video.id}`)
}

// 切换标签页
const handleTabChange = (tab) => {
  activeTab.value = tab
}

// 上传视频
const handleUpload = () => {
  this.router.push('/upload')


}
</script>

<style lang="scss" scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.user-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  background: #fff;

  .user-banner {
    height: 160px;
    background-size: cover;
    background-position: center;
    position: relative;
  }

  .user-info {
    display: flex;
    padding: 20px;
    position: relative;
  }

  .avatar-container {
    position: relative;
    margin-top: -50px;
    margin-right: 20px;

    .user-avatar {
      border: 4px solid #fff;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .level-badge {
      position: absolute;
      bottom: -5px;
      right: -5px;
      background: linear-gradient(45deg, #fb7299, #ff5e7c);
      color: white;
      border-radius: 12px;
      padding: 2px 10px;
      font-size: 12px;
      font-weight: bold;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    }
  }

  .user-details {
    flex: 1;

    .username {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 8px;

      h2 {
        margin: 0;
        font-size: 24px;
        font-weight: 600;
      }
    }

    .signature {
      color: #666;
      font-size: 14px;
      margin-bottom: 15px;
      line-height: 1.5;
    }

    .stats {
      display: flex;
      gap: 25px;

      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;

        .stat-number {
          font-size: 18px;
          font-weight: 600;
          color: #18191c;
        }

        .stat-label {
          font-size: 13px;
          color: #9499a0;
        }
      }
    }
  }
}

.profile-nav {
  margin-bottom: 25px;
  border-bottom: 1px solid #f1f2f3;

  .nav-menu {
    border: none;

    :deep(.el-menu-item) {
      height: 50px;
      line-height: 50px;
      font-size: 15px;
      padding: 0 20px;
      margin: 0 5px;
      color: #61666d;
      transition: all 0.3s;

      &:hover, &.is-active {
        color: #00aeec;
        background: transparent;
        border-bottom: 3px solid #00aeec;
      }

      .el-icon {
        margin-right: 5px;
        font-size: 18px;
      }
    }
  }
}

.profile-content {
  .tab-content {
    padding: 0 10px;
  }

  .section {
    margin-bottom: 30px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }

    .section-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      position: relative;
      padding-left: 12px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        height: 16px;
        width: 4px;
        background: #00aeec;
        border-radius: 2px;
      }
    }

    .bio-content {
      padding: 15px;
      background: #f9fafb;
      border-radius: 6px;
      line-height: 1.7;
      white-space: pre-line;
    }
  }
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.favorites-main {
  display: flex;
  gap: 32px;
}
.favorites-list {
  width: 220px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px 0;
  min-height: 320px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}
.fav-menu {
  background: transparent;
  border: none;
}
.fav-menu-item {
  padding: 10px 24px 10px 20px;
  border-radius: 6px;
  margin-bottom: 6px;
  transition: background 0.2s;
  display: block;
}
.fav-menu-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.fav-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.fav-tags-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-end;
  min-width: 90px;
}
.fav-tags-actions .delete-placeholder {
  width: 32px;
  height: 32px;
  visibility: hidden;
  margin-left: 8px;
}
.favorites-videos {
  flex: 1;
  min-height: 320px;
}
.fav-loading {
  padding: 40px 0;
}
.fav-empty {
  color: #aaa;
  text-align: center;
  padding: 60px 0;
  font-size: 16px;
}

.video-title-cell {
  display: flex;
  align-items: center;

  .cover-thumb {
    width: 80px;
    height: 45px;
    border-radius: 4px;
    margin-right: 10px;
  }

  .title-text {
    font-size: 14px;
    line-height: 1.4;
  }
}

.skeleton-cover {
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, #f2f3f5 25%, #e5e6eb 37%, #f2f3f5 63%);
  background-size: 400% 100%;
  animation: skeleton-loading 1.4s ease infinite;
}

@keyframes skeleton-loading {
  0% {
    background-position: 100% 50%
  }
  100% {
    background-position: 0 50%
  }
}

@media (max-width: 992px) {
  .video-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .favorites-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .video-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .user-info {
    flex-direction: column;
    align-items: center;
    text-align: center;

    .avatar-container {
      margin-top: -80px;
      margin-right: 0;
      margin-bottom: 15px;
    }

    .stats {
      justify-content: center;
    }
  }

  .username {
    justify-content: center;
  }

  .profile-nav .nav-menu {
    overflow-x: auto;
    white-space: nowrap;
  }
}

@media (max-width: 480px) {
  .video-grid {
    grid-template-columns: 1fr;
  }

  .favorites-container .favorite-card {
    flex-direction: column;

    .fav-cover {
      width: 100%;
    }
  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>
